package com.noble.glamour.module.local.chat;

import android.text.TextUtils;

import com.noble.glamour.module.local.chat.msgtype.bean.BaseMessage;
import com.noble.glamour.module.local.chat.msgtype.BaseMessageType;
import com.noble.glamour.module.local.chat.msgtype.type.VideoMessage;
import com.noble.mail.MessageConstant;
import com.noble.glamour.module.logic.application.App;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.invoke.Invoker;
import com.noble.glamour.module.logic.socket.IMProxy;
import com.noble.glamour.module.logic.socket.NetData;
import com.noble.glamour.module.logic.socket.listener.IMListener;
import com.noble.glamour.ui.agora.model.EngineConfig;
import com.noble.library.log.PLogger;
import com.noble.mail.type.NoSaveMsgType;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 接收消息处理类
 * Created by Kind on 2017/4/1.
 */
public class RecMessageMgr implements IMListener {

    public void init() {
        IMProxy.getInstance().attach(this);
    }

    public void release() {
        IMProxy.getInstance().detach(this);
    }

    @Override
    public void onMessage(NetData data) {
        try {
            PLogger.d("reMsg-jsonStr=" + data.getMsgBody());
            JSONObject object = new JSONObject(data.getMsgBody());
            if (data.getFromId() <= 0) {//如果小于或等于0
                data.setFromId(object.optLong("UidFrom"));
            }
            int type = data.getMsgType();
            VideoTransceiverMsg(data);
            BaseMessageType messageType = BaseMessageType.valueOf(type);
            BaseMessage message;
            //基本消息
            if (messageType != null) {
                message = messageType.msgClass.newInstance();
                onSaveSendUI(true, message, data);
            } else {
                message = new BaseMessage();
                onSaveSendUI(false, message, data);
            }
        } catch (Exception e) {
            PLogger.printThrowable(e);
        }
    }

    /**
     * 视频中互发消息处理
     */
    private void VideoTransceiverMsg(final NetData data) {
        if (!ModuleMgr.getRtcEnginMgr().getVideoChat()) return;

        App.activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                handleVideoMsg(data);
            }
        });
    }

    private void handleVideoMsg(NetData data) {
        try {
            EngineConfig config = ModuleMgr.getRtcEnginMgr().getEngineConfig();
            int mtp = data.getMsgType();
            String mct = data.getContent();
            long fid = data.getFromId();
            long msgID = data.getMessageId();

            if (config.mOtherId != fid) return;   // 视频通信时不处理其他用户消息

            // 收到文本消息
            if (mtp == 2 && !TextUtils.isEmpty(mct)) {
                Invoker.getInstance().chatMessageJSCMD(ModuleMgr.getRtcEnginMgr().getEngineConfig().nickname == null ? "" :
                        ModuleMgr.getRtcEnginMgr().getEngineConfig().nickname, mct);

                // 清角标
                ModuleMgr.getChatMgr().sendMailReadedMsg(null, fid);
                ModuleMgr.getChatMgr().updateLocalReadStatus(null, String.valueOf(fid), msgID);
            }

//            // 收到礼物消息
//            if (mtp == 10) {
//                JSONObject giftJo = object.getJSONObject("gift");
//                if (giftJo.optInt("recved") == 1) {
//                    GiftsList.GiftInfo giftInfo = ModuleMgr.getCommonMgr().getGiftLists().getGiftInfo(giftJo.optInt("gift_id"));
//                    ModuleMgr.getChatMgr().updateMsgFStatus(msgID, null);
//                    Invoker.getInstance().giftMessageJSCMD(giftInfo.getPic(), giftInfo.getId(), giftJo.optInt("count"), 0);
//
//                    // 清角标
//                    ModuleMgr.getChatMgr().sendMailReadedMsg(null, fid);
//                    ModuleMgr.getChatMgr().updateLocalReadStatus(null, String.valueOf(fid), object.optLong("d"));
//                }
//            }
//
//            // 转盘消息
//            if (mtp == 27) {
//                JSONObject dataJo = object.getJSONObject("g_data");
//                MsgMgr.getInstance().sendMsg(MsgType.MT_Rtc_Chat_Rotary, dataJo.optInt("wave_index"));
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 消息通知到上层UI
     */
    private void onSaveSendUI(boolean isSave, BaseMessage message, NetData data) throws JSONException {
        PLogger.d(message.getWhisperID());
        message.setSendID(data.getFromId());
        message.setMsgID(data.getMessageId());
        message.setType(data.getMsgType());
        message.parseJson(data.getMsgBody());
        message.setDataSource(MessageConstant.TWO);

        message.setWhisperID(String.valueOf(data.getFromId()));
        //接收特殊消息
        ModuleMgr.getChatListMgr().setSpecialMsg(message);

//        // 弹框消息不通知UI
//        if (BaseMessage.DIALOG_TYPE == message.getType()) {
//            return;
//        }

        // 验证是否是需要保存消息
        if (NoSaveMsgType.getNoSaveMsgType(message.getType()) != null) {
            isSave = false;
        }

        if (isSave) {//是否保存
            message.setInfoJson(null);
            if (BaseMessageType.video.getMsgType() == message.getType()) {
                VideoMessage videoMessage = (VideoMessage) message;
                //   reMsg-jsonStr={"d":167211,"fid":110872900,"mct":"","media_tp":1,"mt":1496199691,"mtp":24,"ru":1,"tid":110872803,"vc_esc_code":3,"vc_id":100000496,"vc_tp":3}
                if (ModuleMgr.getRtcChatMgr().isContain(videoMessage.getVideoID())) {//发送方
                    message.setSendID(App.uid);
                }

                //3拒绝或取消 4挂断（挂断可能会收到不止一次）
                if (videoMessage.getVideoTp() == 3 || videoMessage.getVideoTp() == 4) {
                    ModuleMgr.getRtcChatMgr().remove(videoMessage.getVideoID());
                }
                //{"d":167075,"fid":110872922,"mct":"","media_tp":1,"mt":1495891670,"mtp":24,"ru":1,"tid":110872541,"vc_id":100000459,"vc_tp":1}
                ModuleMgr.getChatMgr().onReceivingVideo((VideoMessage) message);
            } else {
                ModuleMgr.getChatMgr().onReceiving(message);
            }
        } else {
            ModuleMgr.getChatMgr().onChatMsgUpdate(message.getChannelID(), message.getWhisperID(), message);
        }
    }
}